<?php
/**
 * Created by PhpStorm
 * User: @leisen
 * Date: 2022/12/5
 * Time: 11:52 AM
 */

namespace Frieza\Modules\Circle\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Circle\CircleTab as mCircleTab;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\Circle\CircleBaseAdmin as sCircleBaseAdmin;
use Doraemon\service\Circle\CircleTab as sCircleTab;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\service\position\PositionApi;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\UrlParams;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CircleTabController
{
    public function index(Content $content, Request $request, $circleId)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $order = ['id' => 'DESC'];
        $where = ['circle_id' => $circleId, 'status' => mCircleTab::STATUS_NORMAL];
        //查询圈子信息
        $info = sCircleBaseAdmin::getInfo($circleId);
        $list = sCircleTab::getList($where, $order, $limit);
        $list['list'] = self::formatList($list['list'], $circleId);

        return $content
            ->header($info['circle_name'])
            ->breadcrumb(['text' => '圈子Tab管理'])
            ->body($this->formatGrid($list, $circleId));
    }


    public static function formatList($list, $circleId)
    {
        $ids = array_column($list, 'id');
        $rulesMap = PositionApi::activeRules($ids, PositionRules::MODULE_TYPE_CIRCLE_TAB);
        $strData = [
            mCircleTab::SHOW_STATUS_NORMAL => [
                'desc' => mCircleTab::SHOW_STATUS_MAP[mCircleTab::SHOW_STATUS_NORMAL],
                'label' => 'label-success',
            ],
            mCircleTab::SHOW_STATUS_WAIT => [
                'desc' => mCircleTab::SHOW_STATUS_MAP[mCircleTab::SHOW_STATUS_WAIT],
                'label' => 'label-warning',
            ],
            mCircleTab::SHOW_STATUS_HIDDEN => [
                'desc' => mCircleTab::SHOW_STATUS_MAP[mCircleTab::SHOW_STATUS_HIDDEN],
                'label' => 'label-danger',
            ]
        ];
        foreach ($list as &$val) {
            $val['user_profile'] = $rulesMap[$val['id']] ?? [];
            $val['icon_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $val['icon'], ImgUrl::IMAGE_SIZE_OP_ORI);
            $linkData = [
                'id' => $circleId, 'obj_id' => $val['id'], 'type' => sCircleTab::TAB_TYPE_TAB_ID
            ];
            $val['link'] = 'circle/detail?protego=' . urlencode(base64_encode(json_encode($linkData)));
            $nowTime = time();
            $val['show_status'] = mCircleTab::SHOW_STATUS_NORMAL;
            if ($val['start_time'] > $nowTime) {
                $val['show_status'] = mCircleTab::SHOW_STATUS_WAIT;
            }
            if ($val['end_time'] < $nowTime) {
                $val['show_status'] = mCircleTab::SHOW_STATUS_HIDDEN;
            }
            $val['start_time'] = date('Y-m-d H:i:s', $val['start_time']);
            $val['end_time'] = date('Y-m-d H:i:s', $val['end_time']);
            $strInfo = $strData[$val['show_status']];
            $strHtml = '<span class="label ' . $strInfo['label'] . '">' . $strInfo['desc'] . '</span>';
            $strHtml .= '<div class="p-1"></div>';
            if ($val['show_status'] != mCircleTab::SHOW_STATUS_NORMAL) {
                $strHtml .= '<span class="label ' . $strInfo['label'] . '">' . $val['start_time'] . '</span>';
                $strHtml .= '<div class="p-1"></div>';
            }
            $strHtml .= '<span class="label ' . $strInfo['label'] . '">' . $val['end_time'] . '</span>';
            $val['str_html'] = $strHtml;
        }
        return $list;
    }

    public function formatGrid($list, $circleId)
    {
        $gridModel = new pGridDataModel($list['list'], $list['total']);
        Admin::script($this->setScript());
        return Admin::grid($gridModel, function (Grid $grid) use ($circleId) {
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->column('id', 'Id');
            $grid->column('name', '子页面名称');
            $grid->column('icon_url', '子页面图标')->image($this->icon_url, 60);
            $grid->column('sort', '位置');
            $grid->column('show_status', '上线状态')->display(function () {
                return $this->str_html;
            });
            $grid->column('user_profile', '分群信息')->userProfile();

            $grid->column('admin_id', '操作人')->display(function () {
                return Admin::user()->find($this->admin_id)->name;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) use ($circleId) {
                $actions->disableEdit();
                $actions->prepend('<a href="/admin/circle/tab/' . $circleId . '/create?id=' . $actions->row->id . '" class="grid-row-edit"><i class="fa fa-edit">&nbsp;</i></a>');
                $actions->prepend('<a class="fa fa-link" data-link = ' . $actions->row->link . '>复制默认锚点链接&nbsp;</a>  ');
            });
        });
    }

    public function create(Content $content, Request $request, $circleId)
    {
        $info = [];
        $id = 0;
        if ($request->input('id')) {
            $id = $request->input('id');
            $info = sCircleTab::getInfo($request->input('id'));
            $info['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
            $info['end_time'] = date('Y-m-d H:i:s', $info['end_time']);
            $info['user_profile'] = AdmOperationModule::getPositionRulesById($id, PositionRules::MODULE_TYPE_CIRCLE_TAB, true) ?: [];
        }
        $form = new Form($info);
        $form->text('name', '子页面名称')->required()->placeholder('请填写子页面名称');
        $form->imgUpload('icon', '子页面图标', true)
            ->showRemove(false)
            ->help('只支持jpg格式');
        $form->hidden('circle_id')->default($circleId);
        $form->hidden('id')->default($id);
        $form->datetime('start_time', '开始时间')->default(date('Y-m-d H:i:s'))->required();
        $form->datetime('end_time', '结束时间')->default(date('Y-m-d H:i:s'))->required();
        $form->radioButton('sort', '位置')
            ->options(array_combine(range(1, 5), range(1, 5)))->required();
        $form->text('url', 'Url')->required()->placeholder('输入Url');
        $form->userProfile('user_profile', '用户分群')->options()->generate();
        $form->action('/admin/circle/tab/save');
        $desc = empty($request->input('id')) ? '子页面创建' :'子页面编辑';
        return $content->header($desc)
            ->breadcrumb(['text' => '圈子管理', 'url' => 'circle'], ['text' => $desc])
            ->row($form->render());
    }

    public function save(Request $request)
    {
        $params = $request->all();
        $id = $params['id'] ?? 0;
        $data['circle_id'] = $params['circle_id'];
        $data['name'] = $params['name'];
        $data['icon'] = $params['icon'];
        $data['sort'] = $params['sort'];
        $data['start_time'] = strtotime($params['start_time']);
        $data['end_time'] = strtotime($params['end_time']);
        $data['admin_id'] = Admin::user()->id;
//        $data['url'] = $params['url'];
        $data['url'] = (string)UrlParams::addParams($params['url'], ['in_bigtag' => 1]);
        $updId = sCircleTab::save($data, $id);
        if (!$updId) {
            $error = new MessageBag(['title' => '保存失败，请重试']);
            return back()->with(compact('error'))->withInput();
        }
        $userProfile = $request->input('user_profile', []);
        AdmOperationModule::addUserProfile($updId, $userProfile, PositionRules::MODULE_TYPE_CIRCLE_TAB);
        $message = '保存成功';
        $success = new MessageBag(['title' => $message]);
        return redirect("/admin/circle/tab/{$data['circle_id']}")->with(compact('success'));
    }

    public function del($circleId, $id)
    {
        $data = ['status' => mCircleTab::STATUS_DELETE, 'admin_id' => Admin::user()->id];
        $res = sCircleTab::save($data, $id);
        if ($res) {
            return response()->json(
                ['status' => true, 'message' => '删除成功']
            );
        }
        return response()->json([
            'status' => false,
            'message' => "删除失败",
        ]);
    }

    public static function setScript()
    {
        return <<<SCRIPT
        $('.fa-link').unbind('click').click(function(){
            var link = $(this).data('link');
            var tempInput = document.createElement("input");
            tempInput.value = link;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            toastr.success('复制成功', null, {timeOut : 1000}); 
        });
SCRIPT;
    }
}